package com.woniuxy.commons;


import com.woniuxy.annotation.Validate;
import com.woniuxy.enums.CodeEnum;
import com.woniuxy.exception.ActiveCodeException;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.ParameterNameDiscoverer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.validation.BindingResult;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * AOP，用于检查带注解的方法带没带验证码和电话号码
 */
@Aspect
@Component
public class CodeValidateAdvice {


    @Resource
    private StringRedisTemplate srt;


    private AntPathMatcher apm = new AntPathMatcher();


    @Pointcut("@annotation(com.woniuxy.annotation.Validate)")
    public void pt() {

    }

    @Before("pt()")
    public void begin(JoinPoint jp) {

        Object arg = jp.getArgs()[0];

        MethodSignature st = (MethodSignature) jp.getSignature();
        Method method = st.getMethod();
        //获取注解属性
        Validate validate = method.getDeclaredAnnotation(Validate.class);

        String phoneFieldName = validate.phoneFieldName();
        //获取属性值
        String phone = getFieldValueByName(phoneFieldName, arg).toString();


        String codeFieldName = validate.codeFieldName();


        String code = getFieldValueByName(codeFieldName, arg).toString();

        if (code == null || code.trim().equals(""))
            throw new ActiveCodeException(CodeEnum.CODE_NULL_FAIL.getMessage(), CodeEnum.CODE_NULL_FAIL.getCode());
        String mCode = srt.opsForValue().get("pawn:activeCode:phone:" + phone);
        if (mCode == null)
            throw new ActiveCodeException(CodeEnum.SEND_CODE_NULL_FAIL.getMessage(), CodeEnum.SEND_CODE_NULL_FAIL.getCode());

        if (!mCode.equals(code.trim()))
            throw new ActiveCodeException(CodeEnum.CODE_ERROR.getMessage(), CodeEnum.CODE_ERROR.getCode());

    }

    @AfterReturning("pt()")
    public void commit() {

    }

    @AfterThrowing("pt()")
    public void rollback() {

    }

    @After(("pt()"))
    public void close() {

    }


    /**
     * 获取参数列表
     *
     * @param joinPoint
     * @return
     * @throws ClassNotFoundException
     * @throws NoSuchMethodException
     */
    private static Map<String, Object> getFieldsName(JoinPoint joinPoint) {
        // 参数值
        Object[] args = joinPoint.getArgs();
        ParameterNameDiscoverer pnd = new DefaultParameterNameDiscoverer();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String[] parameterNames = pnd.getParameterNames(method);
        Map<String, Object> paramMap = new HashMap<>(32);
        for (int i = 0; i < parameterNames.length; i++) {
            if (args[i] instanceof BindingResult) {

            } else {
                paramMap.put(parameterNames[i], args[i]);
            }
        }
        return paramMap;
    }


    /**
     * 获取属性名数组
     *
     * @param o
     * @return
     */
    private static String[] getFiledName(Object o) {
        Field[] fields = o.getClass().getDeclaredFields();
        String[] fieldNames = new String[fields.length];
        for (int i = 0; i < fields.length; i++) {
//            System.out.println(fields[i].getType());
            fieldNames[i] = fields[i].getName();
        }
        return fieldNames;
    }

    /**
     * 根据属性名获取属性值
     *
     * @param fieldName
     * @param o
     * @return
     */
    private static Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[]{});
            Object value = method.invoke(o, new Object[]{});
            return value;
        } catch (Exception e) {

            return null;
        }
    }
}
